﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using NHibernate.Criterion;
using Senparc.Weixin.MP.Entities;
using System.Collections.Generic;
using Senparc.Weixin.MP.Helpers;
using ZLCMS.Business.Util;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditNewsMaterial : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxMaterial _materialDb;
        protected string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        private void Save()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        _materialDb = new WxMaterial();

                        _materialDb.Title = tb_name.Text;
                        _materialDb.MsgType = "news";
                        _materialDb.CreateDate = DateTime.Now;
                        _materialDb.UpdateDate = DateTime.Now;
                        _materialDb.Status = "1";
                        _materialDb.OwnerAccount = _userAccount;

                        _materialDb.ResponseXml = CreateXml(session, _materialDb);

                        session.Save(_materialDb);
                    }
                    else//修改
                    {
                        _materialDb.Title = tb_name.Text;
                        _materialDb.UpdateDate = DateTime.Now;

                        _materialDb.ResponseXml = "";// CreateXml(session, _materialDb);

                        session.Update(_materialDb);
                    }

                    session.Flush();
                }
                catch (System.Exception ex)
                {
                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _frameHelper.NavTabId,
                forwardUrl = "/SystemManage/Weixin/Material/EditNewsMaterial.aspx?uid=" + _materialDb.Id,
                callbackType = "forward"
            });
        }

        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        _materialDb =  session.CreateCriteria<WxMaterial>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterial>();


                        if (_materialDb == null)
                        {
                            throw new Exception("找不到对应信息.");
                        }

                        grid.DataSource = session.CreateCriteria<WxMaterialNews>().Add(Expression.Eq("MaterialId", _materialDb.Id)).AddOrder(Order.Asc("ShowOrder")).List<WxMaterialNews>();
                        grid.DataBind();
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        }

        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                if (_materialDb != null)
                {
                    tb_name.Text = _materialDb.Title;
                }
            }
        }

        protected string CreateXml(ISession session, WxMaterial mat)
        {
            ResponseMessageNews newsEn = new ResponseMessageNews();

            newsEn.ToUserName = "%TOUSERNAME%";
            newsEn.FromUserName = "%FROMUSERNAME%";
            newsEn.CreateTime = DateTime.Parse("1900-01-01 00:00:00");

            IList<WxMaterialNews> list = session.CreateCriteria<WxMaterialNews>().Add(Expression.Eq("MaterialId", mat.Id)).AddOrder(Order.Asc("ShowOrder")).List<WxMaterialNews>();

            foreach (WxMaterialNews item in list)
            {
                newsEn.Articles.Add(new Article() { Title = item.Title, Description = item.Description, PicUrl = FileKit.FirstFilePath(item.PicUrl), Url = item.Url });
            }

            return EntityHelper.ConvertEntityToXmlString<ResponseMessageNews>(newsEn).Replace("-2209017600", "%CREATETIME%");
        }
    }
}
